import transaction

from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Unicode

from sqlalchemy.exc import IntegrityError
from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import sessionmaker

from zope.sqlalchemy import ZopeTransactionExtension

from sqlalchemy import Text



DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()


from scp.modelo.Permiso import Permiso
from scp.modelo.Usuario import Usuario
from scp.modelo.Rol import Rol
from scp.modelo.Proyecto import Proyecto
from scp.modelo.Fase import Fase
from scp.modelo.Atributo import Atributo


class MyModel(Base):
    __tablename__ = 'models'
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(255), unique=True)
    value = Column(Integer)

    def __init__(self, name, value):
        self.name = name
        self.value = value

class Page(Base):
    """ The SQLAlchemy declarative model class for a Page object. """
    __tablename__ = 'pages'
    id = Column(Integer, primary_key=True)
    name = Column(Text, unique=True)
    data = Column(Text)

    def __init__(self, name, data):
        self.name = name
        self.data = data


def populate():
    session = DBSession()
    model = MyModel(name=u'root', value=55)
    session.add(model)
    session.flush()
    transaction.commit()

def initialize_sql(engine):
    DBSession.configure(bind=engine)
    Base.metadata.bind = engine
    Base.metadata.create_all(engine)
    
    try:
        transaction.begin()
        session = DBSession()
        page = Page('FrontPage', 'This is the front page')
        session.add(page)
        transaction.commit()
    except IntegrityError:
        # already created
        transaction.abort()




